/**
 * 习惯管理相关Mock数据
 */

import { generateId, randomNumber, randomChoice, randomBoolean, randomDate, formatDate, paginate } from '../utils'
import { HABITS_CONFIG } from '@/config'

// 模拟习惯数据
const mockHabits = [
  {
    id: '1',
    name: '早起',
    description: '每天早上6点起床',
    category: 'health',
    type: 'daily',
    priority: 'high',
    targetValue: 1,
    unit: '次',
    reminderTime: '06:00',
    reminderEnabled: true,
    streak: 15,
    bestStreak: 30,
    completedDays: 45,
    totalDays: 60,
    isActive: true,
    createdAt: '2024-01-01T00:00:00.000Z',
    updatedAt: '2024-01-15T06:00:00.000Z'
  },
  {
    id: '2',
    name: '阅读',
    description: '每天阅读30分钟',
    category: 'study',
    type: 'daily',
    priority: 'medium',
    targetValue: 30,
    unit: '分钟',
    reminderTime: '20:00',
    reminderEnabled: true,
    streak: 8,
    bestStreak: 25,
    completedDays: 32,
    totalDays: 45,
    isActive: true,
    createdAt: '2024-01-05T00:00:00.000Z',
    updatedAt: '2024-01-15T20:30:00.000Z'
  },
  {
    id: '3',
    name: '运动',
    description: '每周运动3次',
    category: 'exercise',
    type: 'weekly',
    priority: 'high',
    targetValue: 3,
    unit: '次',
    reminderTime: '18:00',
    reminderEnabled: false,
    streak: 4,
    bestStreak: 12,
    completedDays: 18,
    totalDays: 24,
    isActive: true,
    createdAt: '2024-01-01T00:00:00.000Z',
    updatedAt: '2024-01-14T18:30:00.000Z'
  }
]

// 模拟习惯完成记录
const mockHabitRecords = []

// 生成模拟完成记录
function generateHabitRecords() {
  mockHabits.forEach(habit => {
    const recordCount = randomNumber(20, 50)
    for (let i = 0; i < recordCount; i++) {
      const date = randomDate(new Date(2024, 0, 1), new Date())
      mockHabitRecords.push({
        id: generateId(),
        habitId: habit.id,
        date: formatDate(date, 'YYYY-MM-DD'),
        completed: randomBoolean(0.8),
        value: habit.targetValue,
        note: randomChoice(['', '完成得很好', '有点困难', '状态不错', '需要坚持'], 1),
        createdAt: date.toISOString(),
        updatedAt: date.toISOString()
      })
    }
  })
}

// 初始化记录
generateHabitRecords()

export default {
  // 获取习惯列表
  'GET /habits': async (params = {}) => {
    const { page = 1, pageSize = 20, category, type, isActive } = params
    
    let filteredHabits = [...mockHabits]
    
    // 按分类筛选
    if (category) {
      filteredHabits = filteredHabits.filter(habit => habit.category === category)
    }
    
    // 按类型筛选
    if (type) {
      filteredHabits = filteredHabits.filter(habit => habit.type === type)
    }
    
    // 按状态筛选
    if (isActive !== undefined) {
      filteredHabits = filteredHabits.filter(habit => habit.isActive === isActive)
    }
    
    return paginate(filteredHabits, page, pageSize)
  },
  
  // 创建习惯
  'POST /habits': async (data) => {
    const { name, description, category, type, priority, targetValue, unit, reminderTime, reminderEnabled } = data
    
    // 验证必填字段
    if (!name || !category || !type) {
      throw new Error(JSON.stringify({ code: 1001, message: '习惯名称、分类和类型不能为空' }))
    }
    
    // 检查习惯名称是否已存在
    if (mockHabits.find(habit => habit.name === name)) {
      throw new Error(JSON.stringify({ code: 1004, message: '习惯名称已存在' }))
    }
    
    const newHabit = {
      id: generateId(),
      name,
      description: description || '',
      category,
      type,
      priority: priority || 'medium',
      targetValue: targetValue || 1,
      unit: unit || '次',
      reminderTime: reminderTime || '09:00',
      reminderEnabled: reminderEnabled !== false,
      streak: 0,
      bestStreak: 0,
      completedDays: 0,
      totalDays: 0,
      isActive: true,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }
    
    mockHabits.push(newHabit)
    
    return newHabit
  },
  
  // 更新习惯
  'PUT /habits/:id': async (data, { pathParams }) => {
    const { id } = pathParams
    const habitIndex = mockHabits.findIndex(habit => habit.id === id)
    
    if (habitIndex === -1) {
      throw new Error(JSON.stringify({ code: 1003, message: '习惯不存在' }))
    }
    
    const allowedFields = ['name', 'description', 'category', 'type', 'priority', 'targetValue', 'unit', 'reminderTime', 'reminderEnabled', 'isActive']
    const updates = {}
    
    allowedFields.forEach(field => {
      if (data[field] !== undefined) {
        updates[field] = data[field]
      }
    })
    
    // 检查名称重复（排除自己）
    if (updates.name && mockHabits.find(habit => habit.name === updates.name && habit.id !== id)) {
      throw new Error(JSON.stringify({ code: 1004, message: '习惯名称已存在' }))
    }
    
    mockHabits[habitIndex] = {
      ...mockHabits[habitIndex],
      ...updates,
      updatedAt: new Date().toISOString()
    }
    
    return mockHabits[habitIndex]
  },
  
  // 删除习惯
  'DELETE /habits/:id': async (data, { pathParams }) => {
    const { id } = pathParams
    const habitIndex = mockHabits.findIndex(habit => habit.id === id)
    
    if (habitIndex === -1) {
      throw new Error(JSON.stringify({ code: 1003, message: '习惯不存在' }))
    }
    
    mockHabits.splice(habitIndex, 1)
    
    // 删除相关记录
    const recordIndexes = []
    mockHabitRecords.forEach((record, index) => {
      if (record.habitId === id) {
        recordIndexes.push(index)
      }
    })
    
    recordIndexes.reverse().forEach(index => {
      mockHabitRecords.splice(index, 1)
    })
    
    return { message: '删除成功' }
  },
  
  // 获取习惯详情
  'GET /habits/:id': async (data, { pathParams }) => {
    const { id } = pathParams
    const habit = mockHabits.find(habit => habit.id === id)
    
    if (!habit) {
      throw new Error(JSON.stringify({ code: 1003, message: '习惯不存在' }))
    }
    
    return habit
  },
  
  // 标记习惯完成
  'POST /habits/:id/complete': async (data, { pathParams }) => {
    const { id } = pathParams
    const habit = mockHabits.find(habit => habit.id === id)
    
    if (!habit) {
      throw new Error(JSON.stringify({ code: 1003, message: '习惯不存在' }))
    }
    
    const { date = formatDate(new Date(), 'YYYY-MM-DD'), value, note } = data
    
    // 检查是否已经完成
    const existingRecord = mockHabitRecords.find(record => 
      record.habitId === id && record.date === date
    )
    
    if (existingRecord) {
      if (existingRecord.completed) {
        throw new Error(JSON.stringify({ code: 1004, message: '今日已完成该习惯' }))
      } else {
        // 更新记录
        existingRecord.completed = true
        existingRecord.value = value || habit.targetValue
        existingRecord.note = note || ''
        existingRecord.updatedAt = new Date().toISOString()
      }
    } else {
      // 创建新记录
      const newRecord = {
        id: generateId(),
        habitId: id,
        date,
        completed: true,
        value: value || habit.targetValue,
        note: note || '',
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      }
      mockHabitRecords.push(newRecord)
    }
    
    // 更新习惯统计
    const habitIndex = mockHabits.findIndex(h => h.id === id)
    if (habitIndex !== -1) {
      mockHabits[habitIndex].completedDays += 1
      mockHabits[habitIndex].streak += 1
      if (mockHabits[habitIndex].streak > mockHabits[habitIndex].bestStreak) {
        mockHabits[habitIndex].bestStreak = mockHabits[habitIndex].streak
      }
      mockHabits[habitIndex].updatedAt = new Date().toISOString()
    }
    
    return { message: '完成记录已保存' }
  },
  
  // 取消习惯完成
  'POST /habits/:id/uncomplete': async (data, { pathParams }) => {
    const { id } = pathParams
    const habit = mockHabits.find(habit => habit.id === id)
    
    if (!habit) {
      throw new Error(JSON.stringify({ code: 1003, message: '习惯不存在' }))
    }
    
    const { date = formatDate(new Date(), 'YYYY-MM-DD') } = data
    
    // 查找记录
    const recordIndex = mockHabitRecords.findIndex(record => 
      record.habitId === id && record.date === date
    )
    
    if (recordIndex === -1 || !mockHabitRecords[recordIndex].completed) {
      throw new Error(JSON.stringify({ code: 1003, message: '未找到完成记录' }))
    }
    
    // 更新记录
    mockHabitRecords[recordIndex].completed = false
    mockHabitRecords[recordIndex].updatedAt = new Date().toISOString()
    
    // 更新习惯统计
    const habitIndex = mockHabits.findIndex(h => h.id === id)
    if (habitIndex !== -1) {
      mockHabits[habitIndex].completedDays = Math.max(0, mockHabits[habitIndex].completedDays - 1)
      mockHabits[habitIndex].streak = Math.max(0, mockHabits[habitIndex].streak - 1)
      mockHabits[habitIndex].updatedAt = new Date().toISOString()
    }
    
    return { message: '已取消完成记录' }
  },
  
  // 获取习惯统计数据
  'GET /habits/:id/stats': async (data, { pathParams }) => {
    const { id } = pathParams
    const habit = mockHabits.find(habit => habit.id === id)
    
    if (!habit) {
      throw new Error(JSON.stringify({ code: 1003, message: '习惯不存在' }))
    }
    
    const records = mockHabitRecords.filter(record => record.habitId === id)
    const completedRecords = records.filter(record => record.completed)
    
    // 计算完成率
    const completionRate = records.length > 0 ? (completedRecords.length / records.length * 100).toFixed(1) : 0
    
    // 计算本周完成情况
    const now = new Date()
    const weekStart = new Date(now.getFullYear(), now.getMonth(), now.getDate() - now.getDay())
    const weekRecords = completedRecords.filter(record => {
      const recordDate = new Date(record.date)
      return recordDate >= weekStart
    })
    
    // 计算本月完成情况
    const monthStart = new Date(now.getFullYear(), now.getMonth(), 1)
    const monthRecords = completedRecords.filter(record => {
      const recordDate = new Date(record.date)
      return recordDate >= monthStart
    })
    
    return {
      totalDays: records.length,
      completedDays: completedRecords.length,
      completionRate: parseFloat(completionRate),
      currentStreak: habit.streak,
      bestStreak: habit.bestStreak,
      weeklyCompleted: weekRecords.length,
      monthlyCompleted: monthRecords.length,
      averageValue: completedRecords.length > 0 ? 
        (completedRecords.reduce((sum, record) => sum + record.value, 0) / completedRecords.length).toFixed(1) : 0
    }
  },
  
  // 获取习惯历史记录
  'GET /habits/:id/history': async (params = {}, { pathParams }) => {
    const { id } = pathParams
    const { page = 1, pageSize = 20, startDate, endDate } = params
    
    const habit = mockHabits.find(habit => habit.id === id)
    if (!habit) {
      throw new Error(JSON.stringify({ code: 1003, message: '习惯不存在' }))
    }
    
    let records = mockHabitRecords.filter(record => record.habitId === id)
    
    // 按日期筛选
    if (startDate) {
      records = records.filter(record => record.date >= startDate)
    }
    if (endDate) {
      records = records.filter(record => record.date <= endDate)
    }
    
    // 按日期倒序排列
    records.sort((a, b) => new Date(b.date) - new Date(a.date))
    
    return paginate(records, page, pageSize)
  }
}